package cn.legend.travel.destination.keyword.service.impl;


import cn.legend.travel.destination.keyword.dao.cache.repository.IDistrictCacheRepository;
import cn.legend.travel.destination.keyword.dao.persist.repository.IDistrictRepository;
import cn.legend.travel.destination.keyword.pojo.po.HotMonthDestinationPO;
import cn.legend.travel.destination.keyword.pojo.vo.HotMonthDestinationVO;
import cn.legend.travel.destination.keyword.pojo.vo.KeywordVO;
import cn.legend.travel.destination.keyword.service.IDistrictService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * 处理省市区数据的业务实现类
 *
 * @author java@tedu.cn
 * @version 1.0
 */
@Slf4j
@Service
public class DistrictServiceImpl implements IDistrictService {

    @Autowired
    private IDistrictRepository districtRepository;
    @Autowired
    private IDistrictCacheRepository districtCacheRepository;

    public DistrictServiceImpl() {
        log.debug("创建业务类对象：DistrictServiceImpl");
    }

    @Override
    public List<HotMonthDestinationPO> listByType(String type) {
        List<KeywordVO> list = districtCacheRepository.listByType(type);
        List<HotMonthDestinationPO> lists = new ArrayList<>();
        for (KeywordVO keywordVO : list) {
            HotMonthDestinationPO hotMonthDestinationPO = new HotMonthDestinationPO();
            BeanUtils.copyProperties(keywordVO, hotMonthDestinationPO);
            hotMonthDestinationPO.setMonthDestinationList(districtCacheRepository.listByKId(keywordVO.getId()));

            lists.add(hotMonthDestinationPO);
        }
        return lists;
    }

    @Override
    public void rebuildCache() {
        districtCacheRepository.deleteAll();
        List<KeywordVO> list = districtRepository.selectKeywordAll();
        System.err.println(list);
        for (KeywordVO keywordVO : list) {
            List<KeywordVO> keywordVOs = districtRepository.listByType(keywordVO.getId());
            System.err.println(keywordVOs);
            districtCacheRepository.save(keywordVO.getName(),keywordVOs);
            callListRecursion(keywordVOs);
        }
    }

    /**
     * 递归得到各地区的子级列表数据
     *
     * @param keywordVOs 地区数据
     */
    private void callListRecursion( List<KeywordVO> keywordVOs) {
        for (KeywordVO keywordVO:keywordVOs) {
            Long kId = keywordVO.getId();
            List<HotMonthDestinationVO> list = districtRepository.listByKId(kId);
            if (list.size() > 0) {
                districtCacheRepository.saveListByKId(kId, list);
            }
        }
    }
}
